package com.easymall.web;

import com.easymall.service.ProdService;
import com.easymall.util.BaseFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "ProdDeleteServlet")
public class ProdDeleteServlet extends HttpServlet {

    private ProdService prodService;

    @Override
    public void init() throws ServletException {
        try {
            prodService = BaseFactory.getFactory().getInstance(ProdService.class);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServletException(e.getMessage());
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pidString = request.getParameter("pid");
        try {
            int pid = Integer.valueOf(pidString);
            boolean isExists = prodService.hasProdById(pid);
            if (isExists) {
                boolean isSucces = prodService.deleteProd(pid);
                if (isSucces) {
                    response.getWriter().write("true");
                } else {
                    response.getWriter().write("删除失败");
                }
            } else {
                response.getWriter().write("商品不存在");
            }

        } catch (NumberFormatException e) {
            e.printStackTrace();
            response.getWriter().write("参数错误");
        } catch (SQLException e) {
            e.printStackTrace();
            response.getWriter().write("删除失败, 请稍候重试");
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
